﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using SinsenWeb.Helpers.Providers;
using SinsenWeb.Models;

namespace SinsenWeb.Helpers
{
    public class LoginHelper
    {
        public const string SESSION_KEY_CURRENT_MEMBER = "CurrentMember";

        private static MemberUser GetCurrentUser()
        {
            if (HttpContext.Current == null)
                return null;

            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                return null;

            var provider = Membership.Provider;

            var retval = provider.GetUser(HttpContext.Current.User.Identity.Name, true) as MemberUser;
            return retval;
        }

        public static string GetCurrentUserUsername()
        {
            var user = GetCurrentUser();

            if (user == null)
                return null;

            var retval = user.ProviderUserKey as string;
            return retval;
        }

        public static Member GetCurrentMember()
        {
            if(HttpContext.Current == null
                || HttpContext.Current.Session == null)
            {
                return PerformGetCurrentMember();
            }
            var session = HttpContext.Current.Session;
           
            if(session[SESSION_KEY_CURRENT_MEMBER]==null ||
                session[SESSION_KEY_CURRENT_MEMBER] as Member == null)
            {
                session[SESSION_KEY_CURRENT_MEMBER] = PerformGetCurrentMember();
            }
            var member = session[SESSION_KEY_CURRENT_MEMBER] as Member;
            if(member == null)
            {
                return null;
            }
            if(member.Username!=GetCurrentUserUsername())
            {
                session[SESSION_KEY_CURRENT_MEMBER] = PerformGetCurrentMember();
            }
            return session[SESSION_KEY_CURRENT_MEMBER] as Member;
        }

        private static Member PerformGetCurrentMember()
        {
            var username = GetCurrentUserUsername();
            var member = Member.FindByUsername(username);
            return member;
        }


    }
}
